// API基础URL
const API_BASE_URL = 'http://localhost:3004/api';

// 当前认证令牌
let authToken = null;

// 当前登录用户
let currentUser = null;

// 是否正在初始化
let isInitializing = false;
// 是否已完成初始化
let hasInitialized = false;

// API请求封装函数
async function apiRequest(endpoint, method = 'GET', data = null) {
  console.log('apiRequest函数被调用:', { endpoint, method, hasData: !!data });
  try {
    const headers = {
      'Content-Type': 'application/json'
    };
    
    // 添加认证令牌
    if (authToken) {
      console.log('添加认证令牌到请求头');
      headers['Authorization'] = `Bearer ${authToken}`;
    }
    
    const config = {
      method,
      headers,
      body: data ? JSON.stringify(data) : null
    };
    
    console.log('发送请求:', {
      url: `${API_BASE_URL}${endpoint}`,
      method: config.method,
      headers: { ...config.headers, Authorization: config.headers.Authorization ? 'Bearer ****' : undefined },
      hasBody: !!config.body
    });
    
    const startTime = Date.now();
    const response = await fetch(`${API_BASE_URL}${endpoint}`, config);
    const endTime = Date.now();
    
    console.log(`请求完成，耗时: ${endTime - startTime}ms，状态码: ${response.status}`);
    
    // 处理非2xx响应
    if (!response.ok) {
      console.error('请求返回非成功状态:', response.status);
      const errorData = await response.json().catch(() => ({}));
      console.error('错误数据:', errorData);
      
      // 特殊处理403权限错误，特别是对于/users接口的请求
      if (response.status === 403 && endpoint === '/users') {
        console.warn('非管理员用户访问受限资源，跳过此请求');
        // 返回一个空的成功响应，允许初始化继续
        return { success: true, data: [] };
      }
      
      // 检查是否是编辑学生信息的请求，允许咨询师角色继续
      if (response.status === 403 && endpoint.includes('/students/') && endpoint.includes('PUT')) {
        console.warn('尝试编辑学生信息时遇到权限错误，检查前端权限控制');
        // 如果用户是咨询师，可能是后端权限检查的问题，我们返回一个特殊的响应
        // 让前端知道这是权限问题，但不阻止UI交互
        return { success: false, message: '权限检查错误，请联系管理员' };
      }
      
      throw new Error(errorData.message || `请求失败: ${response.status}`);
    }
    
    const responseData = await response.json();
    console.log('响应数据:', responseData);
    return responseData;
  } catch (error) {
    console.error('API请求错误:', error);
    
    // 对于权限错误，不要显示alert，只在控制台记录
    if (error.message && error.message.includes('没有管理员权限')) {
      console.warn('权限受限错误:', error.message);
    } else {
      // 其他错误仍然显示alert
      alert(`操作失败: ${error.message}`);
    }
    
    throw error;
  }
}

// 数据存储对象
const data = {
    students: [],
    consultations: [],
    users: []
};

// 初始化应用数据
async function initApp() {
  console.log('开始初始化应用，当前用户:', currentUser);
  // 防止重复初始化
  if (isInitializing || hasInitialized) {
    console.log('初始化已在进行中或已完成，跳过重复初始化');
    return;
  }
  
  isInitializing = true;
  
  // 直接初始化数据，避免依赖可能失败的API调用
  data.students = [];
  data.consultations = [];
  data.users = [];
  
  try {
    // 独立处理每个API调用，确保一个失败不会影响其他功能
    
    // 尝试加载考生数据 - 最重要的功能
    try {
      const studentsResponse = await apiRequest('/students');
      if (studentsResponse && studentsResponse.success) {
        data.students = studentsResponse.data || [];
        console.log('成功加载考生数据:', data.students.length, '条');
      }
    } catch (studentsError) {
      console.warn('加载考生数据失败，使用空数据:', studentsError.message);
    }
    
    // 加载咨询记录
    try {
      const consultationsResponse = await apiRequest('/consultations');
      if (consultationsResponse && consultationsResponse.success) {
        data.consultations = consultationsResponse.data || [];
        console.log('成功加载咨询记录:', data.consultations.length, '条');
      }
    } catch (consultationsError) {
      console.warn('加载咨询记录失败，使用空数据:', consultationsError.message);
    }
    
    // 加载用户数据（包含咨询师信息）
    try {
      const usersResponse = await apiRequest('/users');
      if (usersResponse && usersResponse.success) {
        data.users = usersResponse.data || [];
        console.log('成功加载用户数据:', data.users.length, '条');
      }
    } catch (usersError) {
      console.warn('加载用户数据失败，使用空数据:', usersError.message);
    }
    
    // 更新UI - 即使数据加载失败也要更新UI
    try {
      updateStudentSelect();
      updateStudentList();
      updateConsultationList();
      updateStatistics();
      
      // 更新权限控制
      updateUIPermissions();
      
      // 标记初始化完成
      hasInitialized = true;
      console.log('初始化成功完成');
    } catch (uiError) {
      console.error('更新UI失败:', uiError);
    }
  } catch (error) {
    console.error('初始化过程中出现错误:', error);
  } finally {
    isInitializing = false;
    console.log('初始化函数执行完毕');
  }
}

// 保存数据（使用API）
async function saveData(type = 'all') {
    // 不再使用localStorage，而是通过各自的API函数保存
    // 此函数保留以避免现有代码调用出错
    console.log('数据将通过各自的API函数保存');
}

// 更新下拉框
function updateStudentSelect() {
    // 更新考生选择下拉框
    const selectElements = ['consult-student-id', 'filter-student'];
    
    selectElements.forEach(id => {
        const select = document.getElementById(id);
        select.innerHTML = '<option value="">' + (id === 'filter-student' ? '全部考生' : '请选择考生') + '</option>';
        
        data.students.forEach(student => {
            const option = document.createElement('option');
            option.value = student.id;
            option.textContent = `${student.name} (${student.id})`;
            select.appendChild(option);
        });
    });
    
    // 更新咨询师选择下拉框
    const counselorSelect = document.getElementById('student-counselor');
    if (counselorSelect) {
        counselorSelect.innerHTML = '<option value="">请选择咨询师</option>';
        
        // 确保data.users已初始化
        if (!data.users || !Array.isArray(data.users)) {
            data.users = [];
        }
        
        console.log('可用的用户数据:', data.users);
        // 只添加咨询师角色的用户
        const counselors = data.users.filter(user => user.role === '咨询师');
        console.log('筛选出的咨询师:', counselors);
        
        counselors.forEach(counselor => {
            const option = document.createElement('option');
            option.value = counselor.username;
            option.textContent = counselor.username;
            // 如果当前用户是咨询师，默认选中当前用户
            if (currentUser && currentUser.role === '咨询师' && counselor.username === currentUser.username) {
                option.selected = true;
            }
            counselorSelect.appendChild(option); // 确保将选项添加到下拉框中
        });
        
        // 如果没有咨询师选项且当前用户是管理员，显示提示
        if (counselors.length === 0 && currentUser && currentUser.role === '管理员') {
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '暂无咨询师，请先添加';
            option.disabled = true;
            counselorSelect.appendChild(option);
        }
    }
}

// 导出选项配置
const exportFields = [
    { id: 'id', name: '考生ID', defaultSelected: true },
    { id: 'name', name: '姓名', defaultSelected: true },
    { id: 'gender', name: '性别', defaultSelected: true },
    { id: 'ethnicity', name: '民族', defaultSelected: false },
    { id: 'birth', name: '出生日期', defaultSelected: true },
    { id: 'school', name: '学校', defaultSelected: true },
    { id: 'province', name: '所在省份', defaultSelected: false },
    { id: 'subjectCombination', name: '选科组合', defaultSelected: true },
    { id: 'foreignLanguage', name: '外语种类', defaultSelected: false },
    { id: 'parentPhone', name: '家长电话', defaultSelected: false },
    { id: 'householdType', name: '户口类型', defaultSelected: false },
    { id: 'colorBlind', name: '色盲色弱', defaultSelected: false },
    { id: 'visionLeft', name: '左眼视力', defaultSelected: false },
    { id: 'visionRight', name: '右眼视力', defaultSelected: false },
    { id: 'payment', name: '缴费金额', defaultSelected: true },
    { id: 'paymentDate', name: '缴费时间', defaultSelected: true },
    { id: 'earlyBatch', name: '提前批选项', defaultSelected: false },
    { id: 'interests', name: '特长爱好', defaultSelected: false }
];

// 用户认证相关函数

// 登录函数
async function login(username, password) {
  console.log('前端登录函数被调用，用户名:', username, '密码长度:', password.length);
  try {
    console.log('准备发送登录请求到:', API_BASE_URL + '/auth/login');
    console.log('请求数据:', { username, password: '******' });
    
    const response = await apiRequest('/auth/login', 'POST', { username, password });
    console.log('登录请求响应:', response);
    
    if (response.success) {
      console.log('登录成功，用户信息:', response.user);
      currentUser = response.user;
      authToken = response.token;
      localStorage.setItem('authToken', authToken);
      localStorage.setItem('currentUser', JSON.stringify(response.user));
      
      document.getElementById('login-page').style.display = 'none';
      document.getElementById('main-container').style.display = 'block';
      
      // 添加当前用户显示
      updateUserInfo();
      
      // 重置初始化标志，确保重新初始化
      hasInitialized = false;
      // 初始化应用
      await initApp();
      
      return true;
    } else {
      console.log('登录失败，响应success为false');
    }
    return false;
  } catch (error) {
    console.error('登录过程中发生错误:', error);
    alert('登录失败: ' + error.message);
    return false;
  }
}

// 登出函数
function logout() {
  currentUser = null;
  authToken = null;
  localStorage.removeItem('authToken');
  localStorage.removeItem('currentUser');
  // 重置初始化标志，确保下次登录时重新初始化
  hasInitialized = false;
  document.getElementById('login-page').style.display = 'flex';
  document.getElementById('main-container').style.display = 'none';
  
  // 重置咨询师字段为可编辑状态
  const counselorInput = document.getElementById('consult-counselor');
  if (counselorInput) {
    counselorInput.value = '';
    counselorInput.readOnly = false;
    counselorInput.style.backgroundColor = 'white';
    counselorInput.style.cursor = 'text';
  }
}

// 检查是否已登录
async function checkLogin() {
  const savedToken = localStorage.getItem('authToken');
  const savedUser = localStorage.getItem('currentUser');
  
  if (savedToken && savedUser) {
    authToken = savedToken;
    currentUser = JSON.parse(savedUser);
    
    try {
      // 验证token是否有效
      const response = await apiRequest('/auth/me');
      if (response.success) {
        document.getElementById('login-page').style.display = 'none';
        document.getElementById('main-container').style.display = 'block';
        updateUserInfo();
        // 如果尚未初始化，则进行初始化
        if (!hasInitialized && !isInitializing) {
          await initApp();
        }
        return;
      }
    } catch (error) {
      // Token无效，清除并显示登录页
      logout();
    }
  }
  
  document.getElementById('login-page').style.display = 'flex';
  document.getElementById('main-container').style.display = 'none';
}

// 权限控制函数
function hasPermission(action) {
    // 确保用户已登录
    if (!currentUser) {
        return false;
    }
    
    // 管理员拥有所有权限
    if (currentUser.role === '管理员') {
        return true;
    }
    
    // 咨询师的权限限制
    const counselorPermissions = ['view', 'add_consultation', 'export', 'manage_own_consultations', 'edit_student'];
    return counselorPermissions.includes(action);
}

// 创建咨询师账号
async function createCounselor(username, password) {
  try {
    // 创建咨询师时明确指定role为"咨询师"
    const response = await apiRequest('/users', 'POST', { username, password, role: '咨询师' });
    if (response.success) {
      // 重新获取所有用户数据以确保数据同步
      const usersResponse = await apiRequest('/users');
      if (usersResponse.success) {
        data.users = usersResponse.data || [];
      }
      // 更新咨询师列表显示
      await updateCounselorList();
      // 同时更新咨询师选择下拉框，确保新添加的咨询师可以被选择
      updateStudentSelect();
      return { success: true, message: '咨询师账号创建成功' };
    }
    return { success: false, message: response.message || '创建失败' };
  } catch (error) {
    console.error('创建咨询师失败:', error);
    return { success: false, message: error.message };
  }
}

// 更新咨询师列表
async function updateCounselorList() {
  try {
    const tableBody = document.getElementById('counselor-table-body');
    if (!tableBody) return;
    
    // 从API获取咨询师列表
    const response = await apiRequest('/users');
    if (response.success) {
      data.users = response.data || [];
      const counselors = data.users;
      
      tableBody.innerHTML = '';
      
      counselors.forEach((counselor, index) => {
        const row = document.createElement('tr');
        
        row.innerHTML = `
            <td>${index + 1}</td>
            <td>${counselor.username}</td>
            <td>${counselor.role}</td>
            <td>
                <button class="btn btn-sm btn-danger delete-counselor-btn" data-id="${counselor._id}">删除</button>
            </td>
        `;
        
        tableBody.appendChild(row);
      });
      
      // 绑定删除按钮事件
      document.querySelectorAll('.delete-counselor-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
          const counselorId = this.getAttribute('data-id');
          if (confirm('确定要删除此咨询师账号吗？')) {
            await deleteCounselor(counselorId);
          }
        });
      });
    }
  } catch (error) {
    console.error('更新咨询师列表失败:', error);
  }
}

// 删除咨询师
async function deleteCounselor(counselorId) {
  try {
    const response = await apiRequest(`/users/${counselorId}`, 'DELETE');
    if (response.success) {
      // 更新列表
      await updateCounselorList();
      alert(`咨询师删除成功，${response.affectedStudents} 名考生的咨询师信息已更新`);
    }
  } catch (error) {
    alert('删除失败: ' + error.message);
  }
}

// 显示消息
function showMessage(elementId, message, type = 'success') {
    const messageElement = document.getElementById(elementId);
    if (messageElement) {
        messageElement.textContent = message;
        messageElement.style.color = type === 'success' ? '#28a745' : '#dc3545';
        messageElement.style.display = 'block';
        
        // 3秒后隐藏消息
        setTimeout(() => {
            messageElement.style.display = 'none';
        }, 3000);
    }
}

// 更新用户信息显示和权限控制
function updateUserInfo() {
    if (currentUser) {
        // 在导航栏添加用户信息
        const nav = document.querySelector('nav');
        let userInfoElement = document.getElementById('user-info');
        if (!userInfoElement) {
            userInfoElement = document.createElement('div');
            userInfoElement.id = 'user-info';
            userInfoElement.style.float = 'right';
            userInfoElement.style.marginTop = '10px';
            userInfoElement.style.marginRight = '20px';
            userInfoElement.style.color = '#333';
            userInfoElement.style.fontWeight = 'bold';
            nav.appendChild(userInfoElement);
        }
        userInfoElement.innerHTML = `${currentUser.username} (${currentUser.role}) <button id="logout-btn" style="margin-left: 10px; padding: 5px 10px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">登出</button>`;
        
        // 绑定登出按钮事件
        document.getElementById('logout-btn').addEventListener('click', logout);
        
        // 自动预填咨询师字段并设置为只读
        const counselorInput = document.getElementById('consult-counselor');
        if (counselorInput) {
            counselorInput.value = currentUser.username;
            counselorInput.readOnly = true;
            counselorInput.style.backgroundColor = '#f5f5f5';
            counselorInput.style.cursor = 'not-allowed';
        }
        
        // 根据用户角色更新UI权限
        updateUIPermissions();
    }
}

// 根据权限更新UI显示
function updateUIPermissions() {
    // 控制用户管理导航链接和部分
    const userManagementLink = document.getElementById('user-management-link');
    const userManagementSection = document.getElementById('user-management');
    
    if (userManagementLink && userManagementSection) {
        if (currentUser && currentUser.role === '管理员') {
            userManagementLink.style.display = 'block';
            // 初始化咨询师列表
            updateCounselorList();
        } else {
            userManagementLink.style.display = 'none';
            // 确保即使用户手动输入URL也无法访问
            userManagementSection.style.display = 'none';
        }
    }
    
    // 控制添加考生表单
    const addStudentForm = document.getElementById('add-student-form');
    if (addStudentForm) {
        if (!hasPermission('add_student')) {
            addStudentForm.style.display = 'none';
            // 添加提示信息
            let permissionTip = document.getElementById('permission-tip');
            if (!permissionTip && addStudentForm.parentNode) {
                permissionTip = document.createElement('div');
                permissionTip.id = 'permission-tip';
                permissionTip.style.padding = '15px';
                permissionTip.style.backgroundColor = '#f8f9fa';
                permissionTip.style.borderLeft = '4px solid #6c757d';
                permissionTip.style.marginBottom = '15px';
                permissionTip.textContent = '您没有添加考生信息的权限，此功能仅对管理员开放。';
                addStudentForm.parentNode.insertBefore(permissionTip, addStudentForm);
            }
        } else {
            addStudentForm.style.display = 'block';
            // 移除提示信息
            const permissionTip = document.getElementById('permission-tip');
            if (permissionTip && permissionTip.parentNode) {
                permissionTip.parentNode.removeChild(permissionTip);
            }
        }
    }
    
    // 控制导出按钮
    const exportBtn = document.getElementById('export-btn');
    if (exportBtn) {
        exportBtn.style.display = hasPermission('export') ? 'block' : 'none';
    }
    
    // 更新考生列表，根据权限显示/隐藏操作按钮
    updateStudentList();
    
    // 更新咨询记录列表
    updateConsultationList();
}

// 注意：initApp函数已在文件上方定义为异步版本，此处不再重复定义

// 注意：checkLogin函数已在文件上方定义为异步版本，此处不再重复定义

// 显示导出选项对话框
function showExportOptions(students) {
    // 创建对话框
    const dialog = document.createElement('div');
    dialog.className = 'export-dialog';
    dialog.innerHTML = `
        <div class="export-dialog-content">
            <h3>导出选项</h3>
            <div class="export-options">
                <div class="option-group">
                    <h4>基本信息</h4>
                    <div class="option-columns"></div>
                </div>
                <div class="option-group">
                    <h4>成绩信息</h4>
                    <div class="option-columns"></div>
                </div>
            </div>
            <div class="export-dialog-actions">
                <button id="select-all">全选</button>
                <button id="deselect-all">取消全选</button>
                <button id="confirm-export">确认导出</button>
                <button id="cancel-export">取消</button>
            </div>
        </div>
    `;
    
    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        .export-dialog {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .export-dialog-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 700px;
            max-height: 80vh;
            overflow-y: auto;
        }
        .export-dialog-content h3 {
            margin-top: 0;
            margin-bottom: 20px;
            text-align: center;
        }
        .option-group {
            margin-bottom: 20px;
        }
        .option-group h4 {
            margin-top: 0;
            margin-bottom: 10px;
            font-size: 16px;
            color: #333;
        }
        .option-columns {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
        }
        .option-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .export-dialog-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
            padding-top: 10px;
            border-top: 1px solid #ddd;
        }
        .export-dialog-actions button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        #select-all, #deselect-all {
            background-color: #f0f0f0;
            color: #333;
        }
        #select-all:hover, #deselect-all:hover {
            background-color: #e0e0e0;
        }
        #confirm-export {
            background-color: #3498db;
            color: white;
        }
        #confirm-export:hover {
            background-color: #2980b9;
        }
        #cancel-export {
            background-color: #95a5a6;
            color: white;
        }
        #cancel-export:hover {
            background-color: #7f8c8d;
        }
        .group-checkbox {
            margin-left: 20px;
        }
    `;
    document.head.appendChild(style);
    document.body.appendChild(dialog);
    
    // 填充选项
    const basicOptionsContainer = dialog.querySelector('.option-group:nth-child(1) .option-columns');
    const scoreOptionsContainer = dialog.querySelector('.option-group:nth-child(2) .option-columns');
    
    exportFields.forEach(field => {
        if (field.type === 'group') {
            // 成绩组选项
            const groupContainer = document.createElement('div');
            groupContainer.className = 'field-group';
            
            // 组标题复选框
            const groupItem = document.createElement('div');
            groupItem.className = 'option-item group-title';
            groupItem.innerHTML = `
                <input type="checkbox" id="group-${field.id}" ${field.defaultSelected ? 'checked' : ''}>
                <label for="group-${field.id}">${field.name}</label>
            `;
            groupContainer.appendChild(groupItem);
            
            // 组内字段复选框
            const groupFieldsContainer = document.createElement('div');
            groupFieldsContainer.className = 'group-checkbox';
            groupFieldsContainer.style.display = field.defaultSelected ? 'block' : 'none';
            
            field.fields.forEach(subField => {
                const subItem = document.createElement('div');
                subItem.className = 'option-item';
                subItem.innerHTML = `
                    <input type="checkbox" id="field-${subField.id}" ${field.defaultSelected ? 'checked' : ''}>
                    <label for="field-${subField.id}">${subField.name}</label>
                `;
                groupFieldsContainer.appendChild(subItem);
            });
            
            groupContainer.appendChild(groupFieldsContainer);
            scoreOptionsContainer.appendChild(groupContainer);
            
            // 组标题点击事件
            const groupCheckbox = groupItem.querySelector('input');
            groupCheckbox.addEventListener('change', function() {
                const isChecked = this.checked;
                groupFieldsContainer.querySelectorAll('input').forEach(input => {
                    input.checked = isChecked;
                });
                groupFieldsContainer.style.display = isChecked ? 'block' : 'none';
            });
            
            // 组标题点击展开/收起
            groupItem.querySelector('label').addEventListener('click', function() {
                if (groupCheckbox.checked) {
                    groupFieldsContainer.style.display = groupFieldsContainer.style.display === 'none' ? 'block' : 'none';
                }
            });
        } else {
            // 基本信息选项
            const optionItem = document.createElement('div');
            optionItem.className = 'option-item';
            optionItem.innerHTML = `
                <input type="checkbox" id="field-${field.id}" ${field.defaultSelected ? 'checked' : ''}>
                <label for="field-${field.id}">${field.name}</label>
            `;
            basicOptionsContainer.appendChild(optionItem);
        }
    });
    
    // 获取按钮元素
    const selectAllBtn = dialog.querySelector('#select-all');
    const deselectAllBtn = dialog.querySelector('#deselect-all');
    const confirmExportBtn = dialog.querySelector('#confirm-export');
    const cancelExportBtn = dialog.querySelector('#cancel-export');
    
    // 确保所有按钮都存在
    if (!selectAllBtn || !deselectAllBtn || !confirmExportBtn || !cancelExportBtn) {
        console.error('无法找到所有按钮元素');
        return;
    }
    
    // 全选按钮 - 使用匿名函数表达式
    selectAllBtn.onclick = function() {
        const checkboxes = dialog.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(input => {
            input.checked = true;
        });
        const containers = dialog.querySelectorAll('.group-checkbox');
        containers.forEach(container => {
            container.style.display = 'block';
        });
    };
    
    // 取消全选按钮 - 使用匿名函数表达式
    deselectAllBtn.onclick = function() {
        const checkboxes = dialog.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(input => {
            input.checked = false;
        });
        const containers = dialog.querySelectorAll('.group-checkbox');
        containers.forEach(container => {
            container.style.display = 'none';
        });
    };
    
    // 确认导出按钮 - 使用匿名函数表达式
    confirmExportBtn.onclick = function() {
        // 获取选中的字段
        const selectedFields = [];
        
        // 收集基本信息字段
        exportFields.forEach(field => {
            if (!field.type) {
                const checkbox = dialog.querySelector(`#field-${field.id}`);
                if (checkbox && checkbox.checked) {
                    selectedFields.push(field);
                }
            }
        });
        
        // 收集成绩字段
        exportFields.forEach(field => {
            if (field.type === 'group') {
                field.fields.forEach(subField => {
                    const checkbox = dialog.querySelector(`#field-${subField.id}`);
                    if (checkbox && checkbox.checked) {
                        selectedFields.push(subField);
                    }
                });
            }
        });
        
        // 关闭对话框
        if (dialog.parentNode) {
            document.body.removeChild(dialog);
        }
        if (style.parentNode) {
            document.head.removeChild(style);
        }
        
        // 执行导出
        if (selectedFields.length > 0) {
            exportStudentsData(selectedFields, students);
        } else {
            alert('请至少选择一个导出字段！');
        }
    };
    
    // 取消按钮 - 使用匿名函数表达式
    cancelExportBtn.onclick = function() {
        if (dialog.parentNode) {
            document.body.removeChild(dialog);
        }
        if (style.parentNode) {
            document.head.removeChild(style);
        }
    };
}

// 实际执行导出的函数
function exportStudentsData(selectedFields, students) {
    try {
        console.log('开始生成XLSX文件...');
        
        // 准备数据
        const headers = selectedFields.map(field => field.name);
        const dataRows = students.map(student => {
            return selectedFields.map(field => {
                if (field.id.includes('.')) {
                    // 处理成绩字段
                    const [scoreType, subject] = field.id.split('.');
                    if (student.scores && student.scores[scoreType] && student.scores[scoreType][subject]) {
                        return student.scores[scoreType][subject];
                    }
                    return '';
                } else if (field.id === 'earlyBatch') {
                    // 处理提前批选项
                    return student[field.id] ? student[field.id].join('、') : '';
                } else {
                    // 处理普通字段
                    return student[field.id] || '';
                }
            });
        });
        
        // 创建工作表数据（包含标题行）
        const wsData = [headers, ...dataRows];
        
        // 使用SheetJS创建工作簿和工作表
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(wsData);
        
        // 设置列宽（可选，但推荐）
        const colWidths = headers.map(() => ({ wch: 15 })); // 为每个列设置默认宽度
        ws['!cols'] = colWidths;
        
        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '考生信息');
        
        // 生成XLSX文件并下载
        const fileName = `学生信息_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.xlsx`;
        XLSX.writeFile(wb, fileName);
        
        console.log('XLSX文件导出成功，文件名:', fileName);
        alert('学生信息导出成功！');
    } catch (error) {
        console.error('导出XLSX文件失败:', error);
        alert('导出失败: ' + error.message);
    }
}

// 导出学生数据到Excel/CSV（入口函数）
async function exportStudentsToExcel() {
    try {
        // 在显示导出选项前，先获取考生数据
        console.log('开始导出，正在获取考生数据...');
        const response = await apiRequest('/students?_t=' + new Date().getTime());
        
        if (response && response.success) {
            console.log('获取到考生数据，数量:', response.data.length);
            // 将数据作为参数传递给showExportOptions
            showExportOptions(response.data);
        } else {
            console.error('获取考生数据失败:', response);
            alert('获取考生数据失败，无法导出！');
        }
    } catch (error) {
        console.error('导出过程中发生错误:', error);
        alert('导出失败: ' + error.message);
    }
}

// 更新考生列表
// 添加一个标志变量来防止重复执行
let isUpdatingStudentList = false;

async function updateStudentList(filter = '') {
    // 防止函数重复执行
    if (isUpdatingStudentList) {
        console.log('updateStudentList已经在执行中，跳过重复调用');
        return;
    }
    
    isUpdatingStudentList = true;
    
    try {
        console.log('=========== updateStudentList开始执行 ===========');
        console.log('执行时间:', new Date().toISOString());
        console.log('过滤条件:', filter);
        
        const studentList = document.getElementById('student-list');
        if (!studentList) {
            console.error('未找到student-list元素');
            return;
        }
        
        console.log('清空列表前的子节点数量:', studentList.childElementCount);
        
        // 彻底清空列表
        while (studentList.firstChild) {
            studentList.removeChild(studentList.firstChild);
        }
        studentList.innerHTML = ''; // 双重保证
        
        console.log('清空列表后的子节点数量:', studentList.childElementCount);
        
        // 从API获取考生数据 - 添加时间戳防止缓存
        const queryParams = new URLSearchParams();
        if (filter) queryParams.append('search', filter);
        queryParams.append('_t', new Date().getTime()); // 添加时间戳防止缓存
        
        const response = await apiRequest(`/students?${queryParams.toString()}`);
        console.log('获取考生数据响应:', response);
        
        if (response.success) {
            // 使用response.data而不是response.students，与API返回格式保持一致
            let filteredStudents = response.data || [];
            console.log('更新后的考生数据数量:', filteredStudents.length);
            console.log('考生数据详情:', filteredStudents);
            
            // 检查是否有重复ID的考生并去重
            const uniqueStudents = [];
            const seenIds = new Set();
            
            filteredStudents.forEach(student => {
                if (!seenIds.has(student.id)) {
                    seenIds.add(student.id);
                    uniqueStudents.push(student);
                } else {
                    console.warn('发现重复ID的考生数据，已去重:', student.id);
                }
            });
            
            filteredStudents = uniqueStudents;
            console.log('去重后的考生数据数量:', filteredStudents.length);
            
            // 更新本地数据存储
            data.students = filteredStudents;
            
            // 使用Map进行二次去重，确保每个ID只出现一次
            const uniqueStudentMap = new Map();
            filteredStudents.forEach(student => {
                if (uniqueStudentMap.has(student.id)) {
                    console.warn('发现重复ID的考生，已去重:', student.id, student.name);
                } else {
                    uniqueStudentMap.set(student.id, student);
                }
            });
            
            console.log('去重前考生数量:', filteredStudents.length);
            console.log('去重后考生数量:', uniqueStudentMap.size);
            
            // 从Map中渲染唯一的考生
            uniqueStudentMap.forEach((student, id) => {
                console.log('正在渲染考生:', id, student.name);
                const row = document.createElement('tr');
                row.setAttribute('data-student-id', id); // 添加唯一标识便于调试
                
                // 获取成绩显示 - 优先显示高考成绩，其次是三模、二模、一模
                const score = student.scores?.gaokao?.total || student.scores?.mock3?.total || student.scores?.mock2?.total || student.scores?.mock1?.total || '-';
                
                // 根据权限生成操作按钮
                let actionButtons = '<button class="btn btn-info btn-sm" onclick="viewStudentDetail(\'' + student.id + '\')">详情</button>';
                
                // 直接为咨询师添加编辑按钮，不依赖hasPermission函数
                if (currentUser && currentUser.role === '咨询师') {
                    console.log('为咨询师添加编辑按钮:', student.id, student.name);
                    // 确保按钮样式正确且可用
                    actionButtons += ' <button class="btn btn-warning btn-sm" onclick="editStudent(\'' + student.id + '\')" style="cursor: pointer; background-color: #f39c12; border-color: #e67e22; color: white;">编辑</button>';
                } else if (hasPermission('edit_student')) {
                    // 为其他有权限的用户保留原有逻辑
                    console.log('用户有权限编辑考生:', student.id, student.name);
                    actionButtons += ' <button class="btn btn-warning btn-sm" onclick="editStudent(\'' + student.id + '\')" style="cursor: pointer;">编辑</button>';
                }
                
                if (hasPermission('delete_student')) {
                    actionButtons += ' <button class="btn btn-danger btn-sm" onclick="deleteStudent(\'' + student.id + '\')">删除</button>';
                }
                
                row.innerHTML = `
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.gender}</td>
                    <td>${student.school}</td>
                    <td>${student.subjectCombination || '-'}</td>
                    <td>${student.householdType || '-'}</td>
                    <td>${student.counselor || '-'}</td>
                    <td>
                        ${actionButtons}
                    </td>
                `;
                
                // 直接添加行，因为我们已经通过Map进行了去重，理论上不应该有重复
                studentList.appendChild(row);
            });
            
            // 如果没有考生数据，显示提示信息
            if (uniqueStudentMap.size === 0) {
                console.log('无考生数据，显示空状态');
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `<td colspan="8" style="text-align: center; color: #999;">暂无考生数据</td>`;
                studentList.appendChild(emptyRow);
            }
            
            console.log('渲染完成后的子节点数量:', studentList.childElementCount);
            console.log('=========== updateStudentList执行结束 ===========');
        }
    } catch (error) {
        console.error('获取考生列表失败:', error);
        alert('获取考生数据失败: ' + error.message);
    } finally {
        // 无论成功失败，都要重置标志
        isUpdatingStudentList = false;
        console.log('=========== updateStudentList执行结束 ===========');
    }
}

// 更新咨询记录列表
async function updateConsultationList(studentId = '', date = '') {
    try {
        console.log('=========== updateConsultationList开始执行 ===========');
        console.log('执行时间:', new Date().toISOString());
        console.log('过滤条件:', { studentId, date });
        
        const consultationList = document.getElementById('consultation-list');
        if (!consultationList) {
            console.error('未找到consultation-list元素');
            return;
        }
        
        // 双重清空保证
        consultationList.innerHTML = '';
        console.log('清空列表后的子节点数量:', consultationList.childElementCount);
        
        // 首先获取学生数据
        let studentsData = [];
        try {
            const studentsResponse = await apiRequest('/students');
            if (studentsResponse && studentsResponse.success) {
                studentsData = studentsResponse.data || [];
                console.log('获取到学生数据数量:', studentsData.length);
            } else {
                console.warn('获取学生数据失败，将使用空数据');
            }
        } catch (error) {
            console.error('获取学生数据异常:', error);
        }
        
        // 构建查询参数
        const queryParams = new URLSearchParams();
        if (studentId) queryParams.append('studentId', studentId);
        if (date) queryParams.append('date', date);
        
        console.log('API请求URL:', `/consultations?${queryParams.toString()}`);
        
        // 从API获取咨询记录
        const response = await apiRequest(`/consultations?${queryParams.toString()}`);
        console.log('API响应:', response);
        
        if (response && response.success) {
            let filteredConsultations = response.data || [];
            console.log('获取到咨询记录数量:', filteredConsultations.length);
            console.log('咨询记录数据详情:', JSON.stringify(filteredConsultations, null, 2));
            
            // 检查是否有重复ID的咨询记录并去重
            const uniqueConsultations = [];
            const seenIds = new Set();
            
            filteredConsultations.forEach(consultation => {
                if (!seenIds.has(consultation.id)) {
                    seenIds.add(consultation.id);
                    uniqueConsultations.push(consultation);
                } else {
                    console.warn('发现重复ID的咨询记录，已去重:', consultation.id);
                }
            });
            
            filteredConsultations = uniqueConsultations;
            console.log('去重后的咨询记录数量:', filteredConsultations.length);
            
            // 使用Map进行二次去重，确保每个ID只出现一次
            const uniqueConsultationMap = new Map();
            filteredConsultations.forEach(consultation => {
                if (uniqueConsultationMap.has(consultation.id)) {
                    console.warn('发现重复ID的咨询记录，已去重:', consultation.id);
                } else {
                    uniqueConsultationMap.set(consultation.id, consultation);
                }
            });
            
            console.log('去重前咨询记录数量:', filteredConsultations.length);
            console.log('去重后咨询记录数量:', uniqueConsultationMap.size);
            
            // 更新表格标题行的记录数量信息
            // 查找咨询记录列表标题
            const consultationTitle = document.querySelector('h2, h3, h4');
            if (consultationTitle && consultationTitle.textContent.includes('咨询记录列表')) {
                // 如果标题已包含数量信息，先移除
                consultationTitle.textContent = consultationTitle.textContent.replace(/\s*\(\d+条记录\)/, '');
                // 添加数量信息到标题
                consultationTitle.textContent += ` (${uniqueConsultationMap.size}条记录)`;
            } else {
                // 如果找不到标题，使用更紧凑的提示样式
                const oldCountDiv = consultationList.parentNode.querySelector('div[data-role="consultation-count"]');
                if (oldCountDiv) {
                    oldCountDiv.remove();
                }
                
                const countDiv = document.createElement('div');
                countDiv.setAttribute('data-role', 'consultation-count');
                countDiv.style.fontSize = '12px';
                countDiv.style.color = '#666';
                countDiv.style.textAlign = 'right';
                countDiv.style.marginBottom = '5px';
                countDiv.style.padding = '2px 0';
                countDiv.textContent = `${uniqueConsultationMap.size} 条记录`;
                consultationList.parentNode.insertBefore(countDiv, consultationList);
            }
            
            // 在渲染新记录前先清空列表内容，避免重复添加
            consultationList.innerHTML = '';
            
            if (uniqueConsultationMap.size > 0) {
                let index = 0;
                uniqueConsultationMap.forEach((consultation, id) => {
                    console.log('渲染第', index+1, '条咨询记录:', consultation);
                    const row = document.createElement('tr');
                    index++;
                    
                    // 根据权限和咨询记录归属生成操作按钮
                    let actionButtons = '<button class="btn btn-info btn-sm" onclick="viewConsultationDetail(\'' + consultation.id + '\')">详情</button>';
                    
                    // 管理员可以删除所有记录，咨询师只能删除自己的记录
                    if ((currentUser && currentUser.role === '管理员') || 
                        (currentUser && consultation.counselor === currentUser.username)) {
                        actionButtons += ' <button class="btn btn-danger btn-sm" onclick="deleteConsultation(\'' + consultation.id + '\')">删除</button>';
                    }
                    
                    // 格式化日期显示
                    const formattedDate = consultation.date ? new Date(consultation.date).toLocaleDateString() : '-';
                    
                    // 按要求显示单独的考生ID和考生姓名
                    const studentId = consultation.studentId || '-';
                    
                    // 从已加载的学生数据中查找考生姓名
                    let studentName = '-';
                    if (studentId !== '-') {
                        const student = studentsData.find(s => s.id === studentId || s.studentId === studentId);
                        if (student) {
                            studentName = student.name || student.studentName || '-';
                        }
                    }
                    
                    // 获取咨询主题（可能存储在不同字段中）
                    const consultationSubject = consultation.content ? consultation.content.substring(0, 20) + (consultation.content.length > 20 ? '...' : '') : '-';
                    
                    // 获取咨询时长（检查多个可能的字段）
                    let duration = '-';
                    // 检查多个可能的时长字段
                    const durationFields = ['duration', 'consultationTime', 'time', 'minutes', 'consultTime'];
                    for (const field of durationFields) {
                        if (consultation[field]) {
                            duration = consultation[field];
                            break;
                        }
                    }
                    // 如果仍然没有获取到时长，尝试从内容中提取
                    if (duration === '-' && consultation.content) {
                        const timeMatch = consultation.content.match(/\d+分钟/);
                        if (timeMatch) {
                            duration = timeMatch[0].replace('分钟', '');
                        } else {
                            const numMatch = consultation.content.match(/\d+/);
                            if (numMatch) {
                                duration = numMatch[0];
                            }
                        }
                    }
                    
                    // 检查是否有录音数据，如果没有录音则不显示咨询时长
                    const hasAudio = consultation.audio && consultation.audio.trim() !== '';
                    const durationDisplay = hasAudio ? `${duration}分钟` : '-';
                    
                    row.innerHTML = `
                        <td>${studentId}</td>
                        <td>${studentName}</td>
                        <td>${consultationSubject}</td>
                        <td>${durationDisplay}</td>
                        <td>${formattedDate}</td>
                        <td>${consultation.counselor || '-'}</td>
                        <td>
                            ${actionButtons}
                        </td>
                    `;
                    
                    // 添加唯一标识便于调试
                    row.setAttribute('data-consultation-id', consultation.id || 'unknown');
                    consultationList.appendChild(row);
                    console.log('成功添加记录行到DOM，ID:', consultation.id);
                });
                
                console.log('渲染完成后的子节点数量:', consultationList.childElementCount);
            } else {
                // 如果没有咨询记录，显示提示信息
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `<td colspan="7" style="text-align: center; color: #999;">暂无咨询记录</td>`;
                consultationList.appendChild(emptyRow);
                console.log('无咨询记录，显示空状态');
            }
        } else {
            console.error('API返回失败或数据格式错误:', response);
            const errorRow = document.createElement('tr');
            errorRow.innerHTML = `<td colspan="7" style="text-align: center; color: #f00;">获取咨询记录失败：${response?.message || '未知错误'}</td>`;
            consultationList.appendChild(errorRow);
        }
    } catch (error) {
            console.error('获取咨询记录列表异常:', error);
            console.error('错误详情:', error.stack);
            if (consultationList) {
                const errorRow = document.createElement('tr');
                errorRow.innerHTML = `<td colspan="7" style="text-align: center; color: #f00;">获取咨询记录异常：${error.message}</td>`;
                consultationList.appendChild(errorRow);
            }
        } finally {
        console.log('=========== updateConsultationList执行结束 ===========');
    }
}

// 更新统计信息
async function updateStatistics() {
    try {
        // 从API获取统计信息
        const stats = await apiRequest('/statistics', 'GET').then(response => response.data);
        
        // 总考生数
        document.getElementById('total-students').textContent = stats.studentCount || 0;
        
        // 本月咨询次数
        document.getElementById('monthly-consults').textContent = stats.monthlyConsultCount || 0;
        
        // 平均咨询时长
        document.getElementById('avg-consult-time').textContent = `${stats.avgConsultDuration || 0}分钟`;
    } catch (error) {
        console.error('获取统计信息失败:', error);
        // 显示错误信息，但不影响其他功能
        document.getElementById('total-students').textContent = 'N/A';
        document.getElementById('monthly-consults').textContent = 'N/A';
        document.getElementById('avg-consult-time').textContent = 'N/A';
    }
}

// 查看考生详情
async function viewStudentDetail(studentId) {
    try {
        // 从API获取考生详情
        const response = await apiRequest(`/students/${studentId}`);
        
        if (response.success && response.data) {
            const student = response.data;
            
            // 从API获取该考生的咨询记录
            const consultationsResponse = await apiRequest(`/consultations?studentId=${studentId}`);
            const studentConsults = consultationsResponse.success && consultationsResponse.data ? consultationsResponse.data : [];
            
            const modalBody = document.getElementById('modal-body');
            modalBody.innerHTML = `
                <h3>${student.name || '未知考生'} 的详细信息</h3>
                
                <div class="detail-grid">
                    <div>
                        <div class="detail-item"><strong>考生ID:</strong> ${student.id}</div>
                        <div class="detail-item"><strong>性别:</strong> ${student.gender}</div>
                        <div class="detail-item"><strong>民族:</strong> ${student.ethnicity || '-'}</div>
                        <div class="detail-item"><strong>出生日期:</strong> ${student.birth ? new Date(student.birth).toLocaleDateString() : '-'}</div>
                        <div class="detail-item"><strong>毕业学校:</strong> ${student.school}</div>
                        <div class="detail-item"><strong>所在省份:</strong> ${student.province}</div>
                        <div class="detail-item"><strong>选科组合:</strong> ${student.subjectCombination || '-'}</div>
                        <div class="detail-item"><strong>负责咨询师:</strong> ${student.counselor || '-'}</div>
                    </div>
                    <div>
                        <div class="detail-item"><strong>外语种类:</strong> ${student.foreignLanguage || '-'}</div>
                        <div class="detail-item"><strong>家长电话:</strong> ${student.parentPhone || '-'}</div>
                        <div class="detail-item"><strong>户口类型:</strong> ${student.householdType || '-'}</div>
                        <div class="detail-item"><strong>色盲色弱:</strong> ${student.colorBlind || '-'}</div>
                        <div class="detail-item"><strong>左眼视力:</strong> ${student.visionLeft || '-'}</div>
                        <div class="detail-item"><strong>右眼视力:</strong> ${student.visionRight || '-'}</div>
                        <div class="detail-item"><strong>缴费金额:</strong> ${student.payment ? student.payment + ' 元' : '-'}</div>
                        <div class="detail-item"><strong>缴费时间:</strong> ${student.payment && student.payment > 0 && student.paymentDate ? new Date(student.paymentDate).toLocaleDateString() : '-'}</div>
                        <div class="detail-item"><strong>兴趣爱好:</strong> ${student.interests || '-'}</div>
                    </div>
                </div>
                
                <div class="detail-section">
                    <h4>考虑的提前批选项</h4>
                    <div style="padding-left: 20px;">
                        ${student.earlyBatch && student.earlyBatch.length > 0 ? 
                            student.earlyBatch.map(item => `<div>${item}</div>`).join('') : 
                            '<p style="color: #999;">未选择提前批选项</p>'
                        }
                    </div>
                </div>
                
                <div class="detail-section">
                    <h4>成绩统计</h4>
                    ${function() {
                        const scoreTypes = [
                            { key: 'usual', label: '平时成绩' },
                            { key: 'mock1', label: '一模成绩' },
                            { key: 'mock2', label: '二模成绩' },
                            { key: 'mock3', label: '三模成绩' },
                            { key: 'gaokao', label: '高考成绩' }
                        ];
                        
                        // 根据选科组合获取科目名称
                        const getSubjectNames = (combination) => {
                            let subjects = ['选科1', '选科2', '选科3'];
                            
                            switch(combination) {
                                case '物化生':
                                    subjects = ['物理', '化学', '生物'];
                                    break;
                                case '物化政':
                                    subjects = ['物理', '化学', '政治'];
                                    break;
                                case '历政生':
                                    subjects = ['历史', '政治', '生物'];
                                    break;
                                case '历政地':
                                    subjects = ['历史', '政治', '地理'];
                                    break;
                            }
                            
                            return subjects;
                        };
                        
                        return scoreTypes.map(type => {
                            const score = student.scores?.[type.key];
                            if (!score) {
                                return `<div class="score-type"><strong>${type.label}:</strong> -</div>`;
                            }
                            
                            const subjects = getSubjectNames(student.subjectCombination);
                            
                            return `
                                <div class="score-type">
                                    <strong>${type.label}:</strong>
                                    <div class="subject-scores">
                                        <div>总分: ${score.total || '-'}</div>
                                        <div>语文: ${score.chinese || '-'}</div>
                                        <div>数学: ${score.math || '-'}</div>
                                        <div>外语: ${score.english || '-'}</div>
                                        <div>${subjects[0]}: ${score.subject1 || '-'}</div>
                                        <div>${subjects[1]}: ${score.subject2 || '-'}</div>
                                        <div>${subjects[2]}: ${score.subject3 || '-'}</div>
                                    </div>
                                </div>
                            `;
                        }).join('');
                    }()}
                </div>
            
            <div class="detail-section">
                <h4>咨询记录 (${studentConsults.length}条)</h4>
                ${studentConsults.length > 0 ? 
                    studentConsults.map(c => `
                        <div class="card" style="margin-bottom: 15px; padding: 15px;">
                            <div class="detail-item"><strong>日期:</strong> ${c.date ? new Date(c.date).toLocaleString() : '-'}</div>
                            <div class="detail-item"><strong>咨询师:</strong> ${c.counselor || '-'}</div>
                            <div class="detail-item"><strong>主题:</strong> ${c.content ? c.content.substring(0, 50) + (c.content.length > 50 ? '...' : '') : '-'}</div>
                            <div class="detail-item"><strong>内容:</strong> ${c.content || '-'}</div>
                            <div class="detail-item"><strong>下次计划:</strong> ${c.notes || c.nextFollowUp || '-'}</div>
                        </div>
                    `).join('') : 
                    '<p style="color: #999;">暂无咨询记录</p>'
                }
            </div>
        `;
        
        // 显示模态框
        const modal = document.getElementById('detail-modal');
        modal.style.display = 'block';
        }
    } catch (error) {
        console.error('获取考生详情失败:', error);
        alert('获取考生信息失败: ' + error.message);
    }
}

// 查看咨询记录详情
async function viewConsultationDetail(consultationId) {
    try {
        console.log('准备获取咨询详情，ID:', consultationId);
        
        // 显示加载中状态
        const modalBody = document.getElementById('modal-body');
        modalBody.innerHTML = '<div class="text-center"><p>正在加载咨询详情...</p></div>';
        
        // 显示模态框
        const modal = document.getElementById('detail-modal');
        modal.style.display = 'block';
        
        // 从API获取咨询记录详情
        const response = await apiRequest(`/consultations/${consultationId}`);
        console.log('获取咨询详情响应:', response);
        
        if (response.success) {
            const consultation = response.data;
            console.log('获取到的咨询数据:', consultation);
            
            // 检查是否有录音数据
            const hasAudio = consultation.audio && consultation.audio.trim() !== '';
            
            // 获取咨询时长（如果有录音才显示）
            let duration = '-';
            if (hasAudio) {
                const durationFields = ['duration', 'consultationTime', 'time', 'minutes', 'consultTime'];
                for (const field of durationFields) {
                    if (consultation[field]) {
                        duration = consultation[field];
                        break;
                    }
                }
            }
            
            modalBody.innerHTML = `
                <h3>咨询记录详情</h3>
                
                <div class="detail-grid">
                    <div>
                        <div class="detail-item"><strong>考生ID:</strong> ${consultation.studentId}</div>
                        <div class="detail-item"><strong>咨询日期:</strong> ${new Date(consultation.date).toLocaleString()}</div>
                        <div class="detail-item"><strong>咨询师:</strong> ${consultation.counselor}</div>
                        ${hasAudio ? `<div class="detail-item"><strong>咨询时长:</strong> ${duration}分钟</div>` : ''}
                    </div>
                </div>
                
                ${hasAudio ? `
                <div class="detail-section">
                    <h4>录音回放</h4>
                    <audio controls style="width: 100%;">
                        <source src="${consultation.audio}" type="audio/webm">
                        您的浏览器不支持音频元素
                    </audio>
                </div>
                ` : '<div class="detail-section"><p>暂无录音数据</p></div>'}
                
                <div class="detail-section">
                    <h4>咨询内容</h4>
                    <p style="white-space: pre-wrap; line-height: 1.8;">${consultation.content || '无'}</p>
                </div>
                
                <div class="detail-section">
                    <h4>下次计划</h4>
                    <p style="white-space: pre-wrap; line-height: 1.8;">${consultation.notes || '无'}</p>
                </div>
            `;
        } else {
            console.error('API返回错误:', response.message);
            modalBody.innerHTML = `
                <div class="alert alert-danger">
                    <h4>获取失败</h4>
                    <p>错误信息: ${response.message || '未知错误'}</p>
                    <p>请求ID: ${consultationId}</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('获取咨询记录异常:', error);
        modalBody.innerHTML = `
            <div class="alert alert-danger">
                <h4>请求异常</h4>
                <p>错误类型: ${error.name}</p>
                <p>错误信息: ${error.message}</p>
                <p>请求ID: ${consultationId}</p>
                <p>API地址: ${API_BASE_URL}/consultations/${consultationId}</p>
            </div>
        `;
    }
}

// 编辑考生信息
async function editStudent(studentId) {
      // 检查权限 - 允许咨询师角色编辑
      if (!(currentUser && currentUser.role === '咨询师') && !hasPermission('edit_student')) {
          alert('您没有编辑考生信息的权限！');
          return;
      }
      console.log('允许编辑考生信息:', studentId);
    
    try {
        // 从API获取考生信息
        const response = await apiRequest(`/students/${studentId}`, 'GET');
        if (!response.success || !response.data) return;
    
        const student = response.data;
    // 填充表单
    const studentIdElem = document.getElementById('student-id');
    if (studentIdElem) studentIdElem.value = student.id;
    const getElement = (id) => document.getElementById(id);
    const setElementValue = (id, value) => {
        const element = getElement(id);
        if (element) element.value = value;
    };
    
    setElementValue('student-name', student.name);
    setElementValue('student-gender', student.gender);
    setElementValue('student-ethnicity', student.ethnicity || '');
    // 将日期时间格式转换为YYYY-MM-DD格式用于日期输入框
    setElementValue('student-birth', student.birth ? new Date(student.birth).toISOString().split('T')[0] : '');
    setElementValue('student-school', student.school);
    setElementValue('student-province', student.province || '');
    setElementValue('student-subject-combination', student.subjectCombination || '');
    setElementValue('student-foreign-language', student.foreignLanguage || '英语');
    setElementValue('student-parent-phone', student.parentPhone || '');
    setElementValue('student-household-type', student.householdType || '');
    setElementValue('student-payment', student.payment || '');
    setElementValue('student-payment-date', student.paymentDate || '');
    
    
    // 设置咨询师信息
    const counselorSelect = document.getElementById('student-counselor');
    if (counselorSelect) {
        // 更新咨询师下拉框
        updateStudentSelect();
        counselorSelect.value = student.counselor || '';
    }
    
    // 设置提前批选项
    const earlyBatchCheckboxes = document.querySelectorAll('[id^="early-"]');
    earlyBatchCheckboxes.forEach(checkbox => {
        checkbox.checked = student.earlyBatch && student.earlyBatch.includes(checkbox.value);
    });
    
    // 设置各科成绩信息
    if (student.scores) {
        // 平时成绩
        if (student.scores.usual) {
            setElementValue('score-usual-chinese', student.scores.usual.chinese || '');
            setElementValue('score-usual-math', student.scores.usual.math || '');
            setElementValue('score-usual-english', student.scores.usual.english || '');
            setElementValue('score-usual-subject1', student.scores.usual.subject1 || '');
            setElementValue('score-usual-subject2', student.scores.usual.subject2 || '');
            setElementValue('score-usual-subject3', student.scores.usual.subject3 || '');
            setElementValue('score-usual', student.scores.usual.total || '');
        }
        
        // 一模成绩
        if (student.scores.mock1) {
            setElementValue('score-mock1-chinese', student.scores.mock1.chinese || '');
            setElementValue('score-mock1-math', student.scores.mock1.math || '');
            setElementValue('score-mock1-english', student.scores.mock1.english || '');
            setElementValue('score-mock1-subject1', student.scores.mock1.subject1 || '');
            setElementValue('score-mock1-subject2', student.scores.mock1.subject2 || '');
            setElementValue('score-mock1-subject3', student.scores.mock1.subject3 || '');
            setElementValue('score-mock1', student.scores.mock1.total || '');
        }
        
        // 二模成绩
        if (student.scores.mock2) {
            setElementValue('score-mock2-chinese', student.scores.mock2.chinese || '');
            setElementValue('score-mock2-math', student.scores.mock2.math || '');
            setElementValue('score-mock2-english', student.scores.mock2.english || '');
            setElementValue('score-mock2-subject1', student.scores.mock2.subject1 || '');
            setElementValue('score-mock2-subject2', student.scores.mock2.subject2 || '');
            setElementValue('score-mock2-subject3', student.scores.mock2.subject3 || '');
            setElementValue('score-mock2', student.scores.mock2.total || '');
        }
        
        // 三模成绩
        if (student.scores.mock3) {
            setElementValue('score-mock3-chinese', student.scores.mock3.chinese || '');
            setElementValue('score-mock3-math', student.scores.mock3.math || '');
            setElementValue('score-mock3-english', student.scores.mock3.english || '');
            setElementValue('score-mock3-subject1', student.scores.mock3.subject1 || '');
            setElementValue('score-mock3-subject2', student.scores.mock3.subject2 || '');
            setElementValue('score-mock3-subject3', student.scores.mock3.subject3 || '');
            setElementValue('score-mock3', student.scores.mock3.total || '');
        }
        
        // 高考成绩
        if (student.scores.gaokao) {
            setElementValue('score-gaokao-chinese', student.scores.gaokao.chinese || '');
            setElementValue('score-gaokao-math', student.scores.gaokao.math || '');
            setElementValue('score-gaokao-english', student.scores.gaokao.english || '');
            setElementValue('score-gaokao-subject1', student.scores.gaokao.subject1 || '');
            setElementValue('score-gaokao-subject2', student.scores.gaokao.subject2 || '');
            setElementValue('score-gaokao-subject3', student.scores.gaokao.subject3 || '');
            setElementValue('score-gaokao', student.scores.gaokao.total || '');
        }
    }
    
    setElementValue('student-interests', student.interests || '');
    
    // 显示表单
    const formContainer = document.getElementById('student-form-container');
    const studentsSection = document.getElementById('students-section');
    if (formContainer) formContainer.style.display = 'block';
    if (studentsSection) studentsSection.style.display = 'none';
    
    // 如果已有选科组合，更新选科标签名称
    if (student.subjectCombination) {
        // 触发选科标签更新
        updateSubjectLabels();
    }
    } catch (error) {
        console.error('获取考生信息失败:', error);
        alert('获取考生信息失败: ' + error.message);
    }
}

// 删除考生
async function deleteStudent(studentId) {
    // 检查权限
    if (!hasPermission('delete_student')) {
        alert('您没有删除考生信息的权限！');
        return;
    }
    
    if (confirm('确定要删除该考生及其所有咨询记录吗？此操作不可撤销。')) {
        try {
            // 调用API删除考生
            const response = await apiRequest(`/students/${studentId}`, 'DELETE');
            if (response.success) {
                alert('删除成功！');
                // 重新加载考生列表
                await updateStudentList();
            } else {
                alert('删除失败: ' + (response.message || '未知错误'));
            }
        } catch (error) {
            console.error('删除考生失败:', error);
            alert('删除失败: ' + error.message);
        }
    }
}

// 删除咨询记录
async function deleteConsultation(consultationId) {
    try {
        // 获取咨询记录信息（从API）
        const consultation = await apiRequest(`/consultations/${consultationId}`, 'GET');
        
        // 管理员可以删除所有记录，咨询师只能删除自己创建的记录
        if (!hasPermission('delete_consultation') && 
            !(currentUser && consultation && consultation.counselor === currentUser.username)) {
            alert('您没有删除此咨询记录的权限！');
            return;
        }
        
        if (confirm('确定要删除这条咨询记录吗？')) {
            // 调用API删除咨询记录
            await apiRequest(`/consultations/${consultationId}`, 'DELETE');
            alert('删除成功！');
            // 重新加载咨询记录列表
            updateConsultationList();
        }
    } catch (error) {
        console.error('删除咨询记录失败:', error);
        alert('删除失败: ' + error.message);
    }
}

// 生成唯一ID
function generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 录音相关变量
let mediaRecorder;
let audioChunks = [];
let audioBlob = null;
let recordingStartTime = 0;
let recordingDuration = 0;

// 初始化录音功能
function initRecording() {
    const startButton = document.getElementById('start-recording');
    const stopButton = document.getElementById('stop-recording');
    const statusElement = document.getElementById('recording-status');
    const player = document.getElementById('recording-player');
    const audioBlobInput = document.getElementById('audio-blob');
    
    // 开始录音
    startButton.addEventListener('click', async () => {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            mediaRecorder = new MediaRecorder(stream);
            audioChunks = [];
            
            mediaRecorder.ondataavailable = event => {
                if (event.data.size > 0) {
                    audioChunks.push(event.data);
                }
            };
            
            mediaRecorder.onstop = () => {
                // 计算录音时长（分钟）
                recordingDuration = Math.round((Date.now() - recordingStartTime) / 60000);
                
                // 将录音时长设置到咨询时长输入框
                document.getElementById('consult-time').value = recordingDuration;
                
                audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                const audioUrl = URL.createObjectURL(audioBlob);
                player.src = audioUrl;
                player.style.display = 'block';
                
                // 将音频数据转换为Base64存储
                const reader = new FileReader();
                reader.onloadend = () => {
                    audioBlobInput.value = reader.result;
                };
                reader.readAsDataURL(audioBlob);
                
                // 停止所有音轨
                stream.getTracks().forEach(track => track.stop());
            };
            
            mediaRecorder.start();
            startButton.disabled = true;
            stopButton.disabled = false;
            statusElement.textContent = '录音中...';
            statusElement.style.color = 'red';
            
            // 记录开始时间
            recordingStartTime = Date.now();
            
            // 限制录音时长为120分钟（2小时）
            setTimeout(() => {
                if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                    stopRecording();
                    alert('录音已自动停止（达到最大时长限制）');
                }
            }, 7200000);
        } catch (err) {
            console.error('无法访问麦克风:', err);
            alert('无法访问麦克风，请确保已授予麦克风权限');
        }
    });
    
    // 停止录音
    stopButton.addEventListener('click', stopRecording);
}

// 停止录音函数
function stopRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
        document.getElementById('start-recording').disabled = false;
        document.getElementById('stop-recording').disabled = true;
        document.getElementById('recording-status').textContent = '录音已停止';
        document.getElementById('recording-status').style.color = '';
    }
}

// 重置录音
function resetRecording() {
    audioBlob = null;
    recordingStartTime = 0;
    recordingDuration = 0;
    document.getElementById('audio-blob').value = '';
    document.getElementById('recording-player').src = '';
    document.getElementById('recording-player').style.display = 'none';
    document.getElementById('recording-status').textContent = '';
    document.getElementById('start-recording').disabled = false;
    document.getElementById('stop-recording').disabled = true;
    // 重置咨询时长输入框
    document.getElementById('consult-time').value = '';
}

// 重置表单
function resetForm() {
    document.getElementById('add-student-form').reset();
    document.getElementById('student-id').value = generateId();
    
    // 清空所有成绩输入框
    const scoreInputs = document.querySelectorAll('[id^="score-"]');
    scoreInputs.forEach(input => {
        input.value = '';
    });
    
    // 清空提前批选项
    const earlyBatchCheckboxes = document.querySelectorAll('[id^="early-"]');
    earlyBatchCheckboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    
    // 重置选科标签为默认名称
    const examTypes = ['usual', 'mock1', 'mock2', 'mock3', 'gaokao'];
    examTypes.forEach(examType => {
        const label1 = document.querySelector(`label[for="score-${examType}-subject1"]`);
        const label2 = document.querySelector(`label[for="score-${examType}-subject2"]`);
        const label3 = document.querySelector(`label[for="score-${examType}-subject3"]`);
        
        if (label1) label1.textContent = '选科1';
        if (label2) label2.textContent = '选科2';
        if (label3) label3.textContent = '选科3';
    });
}

// 根据选科组合更新选科标签名称
function updateSubjectLabels() {
    const combination = document.getElementById('student-subject-combination').value;
    let subjects = ['选科1', '选科2', '选科3']; // 默认名称
    
    // 根据不同的选科组合设置对应的科目名称
    switch(combination) {
        case '物化生':
            subjects = ['物理', '化学', '生物'];
            break;
        case '物化政':
            subjects = ['物理', '化学', '政治'];
            break;
        case '历政生':
            subjects = ['历史', '政治', '生物'];
            break;
        case '历政地':
            subjects = ['历史', '政治', '地理'];
            break;
    }
    
    // 更新所有考试类型的选科标签
    const examTypes = ['usual', 'mock1', 'mock2', 'mock3', 'gaokao'];
    
    examTypes.forEach(examType => {
        // 更新选科1标签
        const label1 = document.querySelector(`label[for="score-${examType}-subject1"]`);
        if (label1) {
            label1.textContent = subjects[0];
        }
        
        // 更新选科2标签
        const label2 = document.querySelector(`label[for="score-${examType}-subject2"]`);
        if (label2) {
            label2.textContent = subjects[1];
        }
        
        // 更新选科3标签
        const label3 = document.querySelector(`label[for="score-${examType}-subject3"]`);
        if (label3) {
            label3.textContent = subjects[2];
        }
    });
}

// 考试类型折叠/展开功能
function toggleExamType(element) {
    const group = element.closest('.exam-type-group');
    const icon = element.querySelector('.toggle-icon');
    
    if (group.classList.contains('expanded')) {
        group.classList.remove('expanded');
        icon.textContent = '▶';
    } else {
        group.classList.add('expanded');
        icon.textContent = '▼';
    }
}

// 计算指定考试类型的总分
function calculateTotal(examType) {
    // 获取各科成绩
    const chinese = parseFloat(document.getElementById(`score-${examType}-chinese`).value || 0);
    const math = parseFloat(document.getElementById(`score-${examType}-math`).value || 0);
    const english = parseFloat(document.getElementById(`score-${examType}-english`).value || 0);
    const subject1 = parseFloat(document.getElementById(`score-${examType}-subject1`).value || 0);
    const subject2 = parseFloat(document.getElementById(`score-${examType}-subject2`).value || 0);
    const subject3 = parseFloat(document.getElementById(`score-${examType}-subject3`).value || 0);
    
    // 计算总分
    const total = chinese + math + english + subject1 + subject2 + subject3;
    
    // 更新总分输入框
    const totalInput = document.getElementById(`score-${examType}`);
    if (totalInput && !isNaN(total) && total > 0) {
        totalInput.value = Math.round(total); // 四舍五入取整
    } else if (totalInput) {
        totalInput.value = ''; // 如果没有有效分数，清空总分
    }
}

// 为指定考试类型的所有成绩输入框添加事件监听器
function addScoreEventListeners(examType) {
    const subjects = ['chinese', 'math', 'english', 'subject1', 'subject2', 'subject3'];
    
    subjects.forEach(subject => {
        const input = document.getElementById(`score-${examType}-${subject}`);
        if (input) {
            input.addEventListener('input', () => calculateTotal(examType));
        }
    });
}

// 页面加载完成后执行
window.addEventListener('DOMContentLoaded', async () => {
    // 检查登录状态
    await checkLogin();
    
    // 初始化 - 检查登录时已经通过checkLogin调用了initApp()，不需要在此处重复调用
    // 只保留表单提交事件监听器等必要的初始化代码
    // 如果currentUser已存在但页面内容未初始化，可以考虑手动调用initApp()
    
    // 为所有考试类型添加成绩输入事件监听器
    const examTypes = ['usual', 'mock1', 'mock2', 'mock3', 'gaokao'];
    examTypes.forEach(type => addScoreEventListeners(type));
    
    // 表单提交事件 - 添加或编辑考生
    document.getElementById('add-student-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const studentId = document.getElementById('student-id').value;
        const existingStudentIndex = data.students.findIndex(s => s.id === studentId);
        
        // 检查权限
        if (existingStudentIndex === -1) {
            // 添加模式
            if (!hasPermission('add_student')) {
                alert('您没有添加考生信息的权限！');
                return;
            }
        } else {
            // 编辑模式 - 允许咨询师角色编辑
            if (!(currentUser && currentUser.role === '咨询师') && !hasPermission('edit_student')) {
                alert('您没有编辑考生信息的权限！');
                return;
            }
            console.log('允许保存编辑后的考生信息:', studentId);
        }
        
        // 收集提前批选项
        const earlyBatchOptions = [];
        const earlyBatchCheckboxes = document.querySelectorAll('[id^="early-"]:checked');
        earlyBatchCheckboxes.forEach(checkbox => {
            earlyBatchOptions.push(checkbox.value);
        });
        
        const student = {
            id: studentId,
            name: document.getElementById('student-name').value,
            gender: document.getElementById('student-gender').value,
            ethnicity: document.getElementById('student-ethnicity').value,
            birth: document.getElementById('student-birth').value,
            school: document.getElementById('student-school').value,
            province: document.getElementById('student-province').value,
            subjectCombination: document.getElementById('student-subject-combination').value || '未选择',
            foreignLanguage: document.getElementById('student-foreign-language').value,
            parentPhone: document.getElementById('student-parent-phone').value || null,
            householdType: document.getElementById('student-household-type').value,
            colorBlind: document.getElementById('student-color-blind').value !== '否', // 如果是"色盲"或"色弱"则为true，否则为false
            visionLeft: document.getElementById('student-vision-left').value || null,
            visionRight: document.getElementById('student-vision-right').value || null,
            payment: document.getElementById('student-payment').value || null,
            paymentDate: document.getElementById('student-payment-date').value && document.getElementById('student-payment').value ? document.getElementById('student-payment-date').value : null,
            earlyBatch: earlyBatchOptions,
            counselor: document.getElementById('student-counselor').value || null,
            scores: {
            usual: {
                chinese: document.getElementById('score-usual-chinese').value || null,
                math: document.getElementById('score-usual-math').value || null,
                english: document.getElementById('score-usual-english').value || null,
                subject1: document.getElementById('score-usual-subject1').value || null,
                subject2: document.getElementById('score-usual-subject2').value || null,
                subject3: document.getElementById('score-usual-subject3').value || null,
                total: document.getElementById('score-usual').value || null
            },
            mock1: {
                chinese: document.getElementById('score-mock1-chinese').value || null,
                math: document.getElementById('score-mock1-math').value || null,
                english: document.getElementById('score-mock1-english').value || null,
                subject1: document.getElementById('score-mock1-subject1').value || null,
                subject2: document.getElementById('score-mock1-subject2').value || null,
                subject3: document.getElementById('score-mock1-subject3').value || null,
                total: document.getElementById('score-mock1').value || null
            },
            mock2: {
                chinese: document.getElementById('score-mock2-chinese').value || null,
                math: document.getElementById('score-mock2-math').value || null,
                english: document.getElementById('score-mock2-english').value || null,
                subject1: document.getElementById('score-mock2-subject1').value || null,
                subject2: document.getElementById('score-mock2-subject2').value || null,
                subject3: document.getElementById('score-mock2-subject3').value || null,
                total: document.getElementById('score-mock2').value || null
            },
            mock3: {
                chinese: document.getElementById('score-mock3-chinese').value || null,
                math: document.getElementById('score-mock3-math').value || null,
                english: document.getElementById('score-mock3-english').value || null,
                subject1: document.getElementById('score-mock3-subject1').value || null,
                subject2: document.getElementById('score-mock3-subject2').value || null,
                subject3: document.getElementById('score-mock3-subject3').value || null,
                total: document.getElementById('score-mock3').value || null
            },
            gaokao: {
                chinese: document.getElementById('score-gaokao-chinese').value || null,
                math: document.getElementById('score-gaokao-math').value || null,
                english: document.getElementById('score-gaokao-english').value || null,
                subject1: document.getElementById('score-gaokao-subject1').value || null,
                subject2: document.getElementById('score-gaokao-subject2').value || null,
                subject3: document.getElementById('score-gaokao-subject3').value || null,
                total: document.getElementById('score-gaokao').value || null
            }
        },
            interests: document.getElementById('student-interests').value || null
        };
        
        try {
            // 临时禁用更新列表功能，避免在API调用期间自动更新
            const tempIsUpdatingStudentList = isUpdatingStudentList;
            isUpdatingStudentList = true;
            
            try {
                if (existingStudentIndex === -1) {
                    // 添加新考生
                    console.log('开始添加新考生...');
                    const result = await apiRequest('/students', 'POST', student);
                    console.log('添加考生API返回结果:', result);
                    resetForm();
                    alert('考生信息添加成功！');
                } else {
                    // 更新现有考生信息
                    console.log('开始更新考生信息...');
                    const result = await apiRequest(`/students/${studentId}`, 'PUT', student);
                    console.log('更新考生API返回结果:', result);
                    resetForm();
                    alert('考生信息更新成功！');
                }
                
                // 强制清空所有可能的缓存和本地数据
                data.students = [];
                console.log('清空本地数据后，data.students长度:', data.students.length);
                
                // 确保列表容器彻底清空
                const studentList = document.getElementById('student-list');
                if (studentList) {
                    studentList.innerHTML = '';
                    console.log('手动清空列表后，子节点数量:', studentList.childElementCount);
                }
                
                // 短暂延迟后再更新列表，确保DOM状态稳定
                setTimeout(async () => {
                    console.log('延迟后调用updateStudentList');
                    // 重置更新标志，允许函数执行
                    isUpdatingStudentList = false;
                    await updateStudentList();
                }, 100);
            } catch (error) {
                console.error('保存考生信息失败:', error);
                alert('保存失败: ' + error.message);
                // 出错时恢复更新标志
                isUpdatingStudentList = tempIsUpdatingStudentList;
            }
        } catch (error) {
            console.error('保存考生信息失败:', error);
            alert('保存失败: ' + error.message);
        }
    });

// 登录表单提交事件
document.getElementById('login-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const errorElement = document.getElementById('login-error');
    
    try {
        const success = await login(username, password);
        if (success) {
            errorElement.textContent = '';
            document.getElementById('username').value = '';
            document.getElementById('password').value = '';
            // 登录函数内部已经调用了initApp()，不需要再次更新列表
        } else {
            errorElement.textContent = '用户名或密码错误';
        }
    } catch (error) {
        console.error('登录失败:', error);
        errorElement.textContent = '登录失败: ' + error.message;
    }
});

// 页面加载时检查登录状态
window.addEventListener('load', function() {
    // 确保DOM加载完成
    setTimeout(checkLogin, 0);
});
    
    // 表单提交事件 - 添加咨询记录
    document.getElementById('add-consultation-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const consultation = {
            id: generateId(),
            studentId: document.getElementById('consult-student-id').value,
            date: document.getElementById('consult-date').value || new Date().toISOString(),
            duration: document.getElementById('consult-time').value,
            counselor: currentUser ? currentUser.username : document.getElementById('consult-counselor').value,
            content: document.getElementById('consult-content').value, // 内容是必需的
            notes: document.getElementById('consult-notes').value || null,
            // 将topics字段的值合并到content中，确保数据不会丢失
            audio: document.getElementById('audio-blob').value || null
        };
        
        // 如果有主题信息，将其添加到内容前面
        const topics = document.getElementById('consult-topics').value;
        if (topics) {
            consultation.content = `主题: ${topics}\n${consultation.content}`;
        }
        
        try {
            // 调用API保存咨询记录
            await apiRequest('/consultations', 'POST', consultation);
            
            // 重置表单和录音
            e.target.reset();
            resetRecording();
            alert('咨询记录添加成功！');
            
            // 重新加载咨询记录列表
            updateConsultationList();
        } catch (error) {
            console.error('保存咨询记录失败:', error);
            alert('保存失败: ' + error.message);
        }
    });
    
    // 初始化录音功能
    initRecording();
    
    // 搜索考生
    document.getElementById('search-btn').addEventListener('click', async () => {
        const searchTerm = document.getElementById('search-student').value;
        await updateStudentList(searchTerm);
    });
    
    // 导出Excel/CSV
    document.getElementById('export-btn').addEventListener('click', async () => {
        try {
            // 使用已实现的导出功能
            exportStudentsToExcel();
        } catch (error) {
            console.error('导出失败:', error);
            alert('导出失败: ' + error.message);
        }
    });
    
    // 筛选咨询记录
    document.getElementById('filter-btn').addEventListener('click', async () => {
        const studentId = document.getElementById('filter-student').value;
        const date = document.getElementById('filter-date').value;
        await updateConsultationList(studentId, date);
    });
    
    // 导航切换
    const navLinks = document.querySelectorAll('nav a');
    const sections = document.querySelectorAll('main section');
    
    navLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const targetId = link.getAttribute('href');
            
            // 隐藏所有章节
            sections.forEach(section => {
                section.style.display = 'none';
            });
            
            // 显示目标章节
            document.querySelector(targetId).style.display = 'block';
            
            // 更新活动状态
            navLinks.forEach(l => l.classList.remove('active'));
            link.classList.add('active');
        });
    });
    
    // 关闭模态框
    document.querySelector('.close').addEventListener('click', () => {
        document.getElementById('detail-modal').style.display = 'none';
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        if (e.target === document.getElementById('detail-modal')) {
            document.getElementById('detail-modal').style.display = 'none';
        }
    });
    
    // 设置默认日期为今天
    const today = new Date().toISOString().split('T')[0];
    const dateInputs = document.querySelectorAll('input[type="date"]');
    dateInputs.forEach(input => {
        input.value = today;
    });
    
    // 创建咨询师账号表单提交事件
    const addCounselorForm = document.getElementById('add-counselor-form');
    if (addCounselorForm) {
        addCounselorForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const username = document.getElementById('counselor-username').value.trim();
            const password = document.getElementById('counselor-password').value;
            const confirmPassword = document.getElementById('counselor-confirm-password').value;
            
            // 表单验证
            if (!username) {
                showMessage('create-counselor-message', '请输入用户名', 'error');
                return;
            }
            
            if (username.length < 3) {
                showMessage('create-counselor-message', '用户名至少需要3个字符', 'error');
                return;
            }
            
            if (!password) {
                showMessage('create-counselor-message', '请输入密码', 'error');
                return;
            }
            
            if (password.length < 6) {
                showMessage('create-counselor-message', '密码至少需要6个字符', 'error');
                return;
            }
            
            if (password !== confirmPassword) {
                showMessage('create-counselor-message', '两次输入的密码不一致', 'error');
                return;
            }
            
            // 调用创建咨询师函数
            const result = await createCounselor(username, password);
            
            // 显示结果消息
            showMessage('create-counselor-message', result.message, result.success ? 'success' : 'error');
            
            // 如果创建成功，重置表单
            if (result.success) {
                addCounselorForm.reset();
            }
        });
    }
    
    // 点击导航链接时，控制用户管理部分的显示
    document.getElementById('user-management-link')?.addEventListener('click', async function(e) {
        e.preventDefault();
        
        // 隐藏所有主要部分
        document.querySelectorAll('main > section').forEach(section => {
            section.style.display = 'none';
        });
        
        // 只在用户是管理员时显示用户管理部分
        if (currentUser && currentUser.role === '管理员') {
            document.getElementById('user-management').style.display = 'block';
            await updateCounselorList(); // 更新列表
        }
    });
});